package com.xiaochun.jiankangapp.utils;

import android.media.MediaRecorder;
import android.os.Handler;
import android.util.Log;

import com.xiaochun.jiankangapp.base.AppContext;

import java.io.File;


/**
 * 录音工具
 */
public class RecorderUtil {

    private static final String TAG = "RecorderUtil";

    private String mFileName = null;
    private MediaRecorder mRecorder = null;
    private long startTime;
    private long timeInterval;
    private boolean isRecording;
    OnRecordListener mOnRecordListener;
    private int mMaxDuration = 60 * 1000;
    private int mNow;
    Handler mHandler = new Handler();
    int MAX_VU_SIZE = 100;
    Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            int vuSize = MAX_VU_SIZE * mRecorder.getMaxAmplitude() / 32768;
            mOnRecordListener.onVoiceChanged(vuSize, MAX_VU_SIZE);
            mHandler.postDelayed(mRunnable, 30);
        }
    };
    private boolean mCalledStopListener = false;
    Runnable mTimeUsingRunnable = new Runnable() {
        @Override
        public void run() {
            mNow += 1000;
            if (mOnRecordListener != null) {
                mOnRecordListener.onTimeUsing(mNow);
            }
            if (mNow >= mMaxDuration) {
                stopRecording();
            } else {
                mHandler.postDelayed(mTimeUsingRunnable, 1000);
            }
        }
    };

    public RecorderUtil() {
    }

    public int getMaxDuration() {
        return mMaxDuration;
    }

    public void setMaxDuration(int maxDuration) {
        mMaxDuration = maxDuration;
    }

    /**
     * 开始录音
     */
    public void startRecording() {
        mFileName = AppContext.globalContext().getFilesDir().getAbsolutePath() + File.separator + System.currentTimeMillis() + ".m4a";
        if (isRecording) {
            mRecorder.release();
            mRecorder = null;
        }
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mRecorder.setOutputFile(mFileName);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        mRecorder.setMaxDuration(mMaxDuration);
        startTime = System.currentTimeMillis();
        mNow = 0;
//        mHandler.postDelayed(mTimeUsingRunnable, 1000);
        mRecorder.setOnInfoListener(new MediaRecorder.OnInfoListener() {
            @Override
            public void onInfo(MediaRecorder mr, int what, int extra) {
            }
        });
        try {
            mRecorder.prepare();
            mRecorder.start();
            isRecording = true;
            mCalledStopListener = false;
            mHandler.postDelayed(mRunnable, 30);
        } catch (Exception e) {
            Log.e(TAG, "prepare() failed");
        }

    }

    public void setOnRecordListener(OnRecordListener onRecordListener) {
        mOnRecordListener = onRecordListener;
    }


    /**
     * 停止录音
     */
    public void stopRecording() {
        timeInterval = System.currentTimeMillis() - startTime;
        try {
            mHandler.removeCallbacks(mRunnable);
            mHandler.removeCallbacks(mTimeUsingRunnable);
            if (timeInterval > 1000) {
                try {
                    mRecorder.stop();
                } catch (Exception e) {

                }
            }
            if (mOnRecordListener != null && !mCalledStopListener) {
                mOnRecordListener.onAutoStopRecord(mFileName, timeInterval);
                mCalledStopListener = true;
            }

            mRecorder.release();
            mRecorder = null;
            isRecording = false;
        } catch (Exception e) {
            Log.e(TAG, "release() failed");
        }
    }


    /**
     * 获取录音文件地址
     */
    public String getFilePath() {
        return mFileName;
    }


    /**
     * 获取录音时长,单位秒
     */
    public long getTimeInterval() {
        return timeInterval / 1000;
    }


    public interface OnRecordListener {

        void onVoiceChanged(int vuSize, int max_vu_size);

        void onAutoStopRecord(String filePath, long duation);

        void onTimeUsing(int nowTimeSecond);
    }


}
